package com.ym.pms.security.service;

import com.ym.pms.model.SysRole;
import com.ym.pms.model.SysUser;
import com.ym.pms.security.entity.SysUserDetails;
import com.ym.pms.service.SysUserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @Author: xybh
 * @Description:
 * @Date: Created in 10:57 2020/12/21
 * @Modified:
 */
@Service
public class SysUserDetailsService implements UserDetailsService {

    @Autowired
    private SysUserService sysUserService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        SysUser sysUser = sysUserService.findUserByUserId(Long.parseLong(username));
        if (sysUser != null) {
            SysUserDetails sysUserDetails = new SysUserDetails();
            BeanUtils.copyProperties(sysUser, sysUserDetails);

            Set<GrantedAuthority> authorities = new HashSet<>();

            List<SysRole> roleList = sysUserService.findRoleByUserId(sysUserDetails.getUId());
            roleList.forEach(role -> {
                authorities.add(new SimpleGrantedAuthority("ROLE_"+role.getRoleName()));
            });

            sysUserDetails.setAuthorities(authorities);

            return sysUserDetails;
        }
        return null;
    }
}
